package com.xy.p2p.action.front;



import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xy.common.page.Pagination;
import com.xy.common.util.DictUtils;
import com.xy.common.web.CookieUtils;
import com.xy.core.web.WebErrors;
import com.xy.gateway.model.EpayGateSetting;
import com.xy.p2p.model.Tmember;
import com.xy.p2p.model.Tmemberassetaccount;
import com.xy.p2p.model.Trecharge;
import com.xy.p2p.service.TmemberassetaccountService;
import com.xy.p2p.service.TrechargeService;



@Controller
public class TrechargeAction{
	private static final Logger log = LoggerFactory.getLogger(TrechargeAction.class);
	public TrechargeAction() {
	}
 
 
 	/**
	 * 充值输入页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/member/rechargeInit.jspx")
	public String add(HttpServletRequest request, ModelMap model) {
		model.addAttribute("requestconfList", epayGateSetting.getRequestConfigList("0"));
		Tmember tmember = (Tmember)request.getSession().getAttribute(TmemberAction.AUTH_KEY);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Tmember", tmember);
		Tmemberassetaccount account = tmemberassetaccountService.getTmemberassetaccount(map).get(0);
		model.addAttribute("balance", account.getBalance());
//		model.addAttribute("tmember",tmember);
		//获取用户余额
//		double balance =0;
//		Set<Object> set =tmember.getTmemberassetaccounts();
//		while(set.iterator().hasNext()){
//			balance = (Double)set.iterator().next();
//		}
//		model.addAttribute("balance", balance);
		//
//        setDict(model);
		//用于导航栏
		model.addAttribute("dis", 4);
		return "rechargePage.html";
	}
	
	
	/**
	 * 进入手工充值页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/member/rechargeLabour.jspx")
	public String rechargeLabour(HttpServletRequest request, ModelMap model) {
		//用于导航栏
		model.addAttribute("dis", 5);
		return "/front/member/rechargeLabour.html";
	}
	/**
	 * 充值提交
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/member/doRecharge.jspx")
	public String doRecharge(HttpServletRequest request, ModelMap model) throws Exception{
		Tmember user = (Tmember) request.getSession().getAttribute(TmemberAction.AUTH_KEY);
		 
		
		SimpleDateFormat simpledateformat = new SimpleDateFormat(
		"yyyyMMddhhmmssSSS");
           String s = simpledateformat.format(new Date());

		String sid=request.getParameter("bankcode");
		String thirdpay_sid=request.getParameter("USETHIRDPAY");
		String paytype=request.getParameter("paytype");
		Date d=new Date();
		String CDATE=new SimpleDateFormat("yyyy-MM-dd").format(d);
//		String bankcode=request.getParameter("bankcode");
		String PAYMENT=request.getParameter("PAYMENT");
		String curr="2";
		String orderid=s;
		String THIRDPAYBANKID="";
		
		if(thirdpay_sid!=null&&!thirdpay_sid.trim().equals("")){
			THIRDPAYBANKID=EpayGateSetting.getThirdpaybankIdByPK(thirdpay_sid,sid , paytype);
			 //UMBPAY特殊处理, paytype为1的商户端选择银行，2为UMBPAY端选择银行
			 if(thirdpay_sid.equals("UMBPAY"))
			 { 
				 paytype="1";
			 } else if(thirdpay_sid.equals("allinpay"))
			 { 
				 //allinpay特殊处理, paytype为2的商户端选择银行，1为allinpay端选择银行
				 paytype="2";
				 model.addAttribute("THIRDpayType",paytype.equals("2")?"1": "4");
				 
			 }
			 sid=thirdpay_sid;
		}
		
		Trecharge trecharge=new Trecharge();
		trecharge.setCurr(curr);
		trecharge.setMemberid(user.getMemberid());
		trecharge.setTruename(user.getTruename());
		trecharge.setOrderid(orderid);
		trecharge.setSid(sid);
		trecharge.setStatus("00");
		trecharge.setTransdate(d);
		trecharge.setAmount(PAYMENT);	
		trechargeService.save(trecharge);
		
		model.addAttribute("sid",sid);
		model.addAttribute("paytype",paytype);
		model.addAttribute("CDATE",CDATE);
		model.addAttribute("PAYMENT",PAYMENT);
		model.addAttribute("curr",curr);
		model.addAttribute("ORDERID",orderid);
		model.addAttribute("THIRDPAYBANKID",THIRDPAYBANKID);
		
//        setDict(model);
		return "rechargeProcessing.html";
	}
	
	@RequestMapping("/rechargeFinish.jspx")
	public String rechargeFinish(HttpServletRequest request, ModelMap model) throws Exception{
		Object valid = request.getAttribute("valid");
		if (valid == null) {
			throw new Exception("无效请求");
		}
		if (new Date().getTime() - Long.valueOf(valid.toString()) > 10000) {
			throw new Exception("请求失效");
		}
		String AMOUNT=request.getParameter("AMOUNT");
		String ORDERID=request.getParameter("ORDERID");
		String   STATUS=request.getParameter("STATUS");
		String   returnMsg=request.getParameter("USRMSG");
		
		if(ORDERID==null||ORDERID.equals("")){
			throw new Exception("无效数据");
		}
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("orderid", ORDERID);
	 List<Trecharge> list=	trechargeService.getTrecharge(map);
	 if(list.size()==0){
		 throw new Exception("没有查到订单数据");
	 }
	 if(list.size()>1){
		 throw new Exception("订单数据有误");
	 }
	 Trecharge trecharge=list.get(0);
	 
	 if(!trecharge.getAmount().equals(AMOUNT)){
		 log.debug("orderid:"+trecharge.getOrderid()+ ",request:"+trecharge.getAmount()+", return:"+AMOUNT);
		 throw new Exception("返回金额有误,请与管理员联系!");
	 }

	 if( trecharge.getReturnDate()!=null){
		 log.debug("orderid:"+trecharge.getOrderid()+ ",returnDate:"+trecharge.getReturnDate());
//		 throw new Exception("订单已处理，请勿重复提交!");
	 }else
	 {
		 log.debug("orderid:"+trecharge.getOrderid() +",status:"+trecharge.getStatus() + ",returnDate:"+trecharge.getReturnDate());
		 trecharge.setStatus(STATUS);
		  trecharge.setReturnDate(new Date());
		  trecharge.setReturnMsg(returnMsg);
		 trechargeService.save(trecharge);
	 }
	
	 
		 return "rechargeFinish.html";
	}
	
//	@RequestMapping("/rechargeFinishTTT.jspx")
//	public String rechargeFinishTTT(HttpServletRequest request, ModelMap model){
//		return "rechargeFinish.html";
//	}
	
	 
	/**
	 * 充值查询（分页）
	 * 
	 * @param trecharge
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/member/v_trechargeList.jspx")
	public String listPage(Trecharge trecharge, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		if (pageNo == null)
			pageNo = 1;
		Tmember user = (Tmember) request.getSession().getAttribute(TmemberAction.AUTH_KEY);
		Map<String,Object>  m=toMap(trecharge);
		m.put("memberid", user.getMemberid());
		m.put("status", "01");
		Pagination pagination = trechargeService.getTrechargeByPage(m,
				pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
        setDict(model);
        //用于导航栏
        model.addAttribute("dis", 6);
		return "rechargeList.html";
	}

	/**
	 * 充值查询
	 * 
	 * @param trecharge
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_trechargeList1.do")
	public String list(Trecharge trecharge, HttpServletRequest request, ModelMap model) {
		List<Trecharge> list = trechargeService.getTrecharge(toMap(trecharge));
		model.addAttribute("list", list);
        setDict(model);
		return "trechargeList";
	}


 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param trecharge
	 * @return
	 */	private Map<String,Object> toMap(Trecharge trecharge){
		Map<String,Object> map=new HashMap<String, Object>();
      		if(trecharge.getFlowno()!=null&&!trecharge.getFlowno().equals("")){
			map.put("flowno", trecharge.getFlowno());
		}
		if(trecharge.getOrderid()!=null&&!trecharge.getOrderid().equals("")){
			map.put("orderid", trecharge.getOrderid());
		}
		 
		if(trecharge.getAccountid()!=null&&!trecharge.getAccountid().equals("")){
			map.put("accountid", trecharge.getAccountid());
		}
		if(trecharge.getAmount()!=null&&!trecharge.getAmount().equals("")){
			map.put("amount", trecharge.getAmount());
		}
		if(trecharge.getCurr()!=null&&!trecharge.getCurr().equals("")){
			map.put("curr", trecharge.getCurr());
		}
		if(trecharge.getTransdate()!=null&&!trecharge.getTransdate().equals("")){
			map.put("transdate", trecharge.getTransdate());
		}
		if(trecharge.getSid()!=null&&!trecharge.getSid().equals("")){
			map.put("sid", trecharge.getSid());
		}
		if(trecharge.getThirdsid()!=null&&!trecharge.getThirdsid().equals("")){
			map.put("thirdsid", trecharge.getThirdsid());
		}
		 
		return map;
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
		private void setDict(ModelMap model){
		      model.addAttribute("statusMap", DictUtils.getDictByType(DictUtils.TRECHARGE_STATUS));		
			}

	/**
	 * 数据校验
	 * @param model
	 */
	private WebErrors validateSave(Trecharge trecharge, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		/**if (errors.ifOutOfLength(username, "username", 1, 100)) {
			return errors;
		}  */    
		return errors;
	}

   
      
	@Resource
	private TrechargeService trechargeService;   
	@Resource
	private EpayGateSetting epayGateSetting;   
	@Resource
	private TmemberassetaccountService tmemberassetaccountService;
}